<?php

class Sgit_Acl extends Zend_Acl
{


    function __construct()
    {
        $acl = $this;

        $resources = new Application_Model_AclResources();
        $usuarios = new Application_Model_Usuario();
        $roles = new Application_Model_AclRolesUser();
        $grupos = new Application_Model_AclGroup();
        $accesos = new Application_Model_AclAccesos();


        //cargo roles grupos
        $rows = $grupos->getAll(array('id < ?' => 1000));

        foreach ($rows as $v)
        {
            $rol = 'group_' . $v['id'];
            if (!$acl->hasRole($rol))
            {
                $acl->addRole(new Zend_Acl_Role($rol));
            }
        }

        //cargo resources
        $rows = $resources->getAll();

        foreach ($rows as $v)
        {

            $key_parent = $v['parent'];
            $key_resource = $v['resource'];

            if (!$acl->has($key_parent))
            {
                if (!empty($key_parent))
                {
                    $acl->add(new Zend_Acl_Resource($key_parent));
                }
            }

            if (!$acl->has($key_resource))
            {
                $acl->add(new Zend_Acl_Resource($key_resource), $key_parent);
            }


            //si check_auth en bd=0 se le permite el acceso
            if ($v['check_auth'] == 0)
            {
                $acl->allow(null, $key_resource);
            }
        }




        //cargo roles usuarios y sus padres
        $rows = $usuarios->getAll();
        foreach ($rows as $v)
        {
            $where2['id_user = ? '] = $v['id'];
            $where2['id_group < ? '] = 1000;
            $filas = $roles->getCol('id_group', $where2, null, 'id_group');

            foreach ((array )$filas as $id_group)
            {
                $rol = 'group_' . $id_group;
                if ($acl->hasRole($rol))
                {
                    $parents[] = $rol;
                }

            }

            $acl->addRole(new Zend_Acl_Role($v['id']), $parents);
            unset($parents);
        }


        //permisos

        //superuser acceso a todos los recursos
        $acl->allow('group_100', null);

        $acc = $accesos->getAll();

        foreach ($acc as $v)
        {

            if ($acl->hasRole($v['id_rol']) && $acl->has($v['id_resource']))
            {
                $v['allow'] ? $acl->allow($v['id_rol'], $v['id_resource']) : $acl->deny($v['id_rol'], $v['id_resource']);
            }
        }

    }

    function getRules($resource = null, $role = null)
    {


        $rules = $this->_rules['byResourceId'][$resource]['byRoleId'];
        foreach ((array )$rules as $k => $v)
        {
            if (is_numeric($k))
                $acceso['user'][] = $k;
            else
                $acceso['group'][] = str_replace('group_', '', $k);

        }

        return $acceso;

    }


}
